package com.boco.pciv.service.shiro;

import cn.hutool.core.util.StrUtil;
import com.boco.pciv.core.entity.Constants;
import com.boco.pciv.core.security.LoginUser;
import com.boco.pciv.core.util.UploadFileUtil;
import com.boco.pciv.entity.sys.ResInfo;
import com.boco.pciv.entity.sys.RoleBasicInfo;
import com.boco.pciv.mapper.shiro.IShiroMapper;
import com.boco.pciv.mapper.sys.IResMapper;
import com.boco.pciv.mapper.sys.IRoleMapper;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class MyUserRealm extends AuthorizingRealm {
    @Autowired
    IShiroMapper mapper;
    @Autowired
    IRoleMapper roleMapper;
    @Autowired
    IResMapper resMapper;
    /**
     * 授权(验证权限时调用)
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        LoginUser user = (LoginUser)principals.getPrimaryPrincipal();
        String userId = user.getUserId();

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //页面权限
        //系统管理员，拥有全部权限
        if(userId.equalsIgnoreCase(Constants.SysAdminUserId)){
            List<ResInfo> resInfos = resMapper.queryList(new HashMap<>());
            for (ResInfo resInfo : resInfos) {
                if (StrUtil.isNotBlank(resInfo.getUrl())){
                    info.addStringPermission(resInfo.getUrl());
                }
            }
        }
        else{
            List<ResInfo> resInfos = resMapper.queryListByUser(userId);
            for (ResInfo resInfo : resInfos) {
                if (StrUtil.isNotBlank(resInfo.getUrl())){
                    info.addStringPermission(resInfo.getUrl());
                }
            }
        }

//        //操作权限
//        Set<String> permsSet = new HashSet<>();
//        for(String perms : permsList){
//            if(StrUtil.isBlank(perms)){
//                continue;
//            }
//            permsSet.addAll(Arrays.asList(perms.trim().split(",")));
//        }

        return info;
    }

    /**
     * 认证(登录时调用)
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken)authcToken;
        LoginUser user = mapper.queryOne(token.getUsername());
        if (user==null){
            throw new UnknownAccountException("账号或密码不正确");
        }
        //账号锁定
        //1:激活，2:锁定，3:删除
        if(user.getState()== 2){
            throw new LockedAccountException("账号已被锁定,请联系管理员");
        }
        else if (user.getState()==3){
            throw new UnknownAccountException("账号或密码不正确");
        }
        if (StrUtil.isNotBlank(user.getPic())){
            user.setPic(UploadFileUtil.getUploadFilePath("head",user.getPic()));
        }
        else{
            //默认头像
            user.setPic("images/0.jpg");
        }

        List<RoleBasicInfo> roles = roleMapper.queryByUser(user.getUserId());
        List<String> roleIds= new ArrayList<>();
        for (RoleBasicInfo role : roles) {
            roleIds.add(role.getRoleId());
        }
        user.setRoleIds(roleIds.toArray(new String[roleIds.size()]));

        ByteSource solt = ByteSource.Util.bytes(ShiroUtils.genSalt(user.getUserId()));

        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user,
                user.getPassword(),
                solt,
                getName());
        return info;
    }
}
